# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError, KspayError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://pay.886pay.com/api/pay_create?time={}&sign={}'
_QUERY_GATEWAY = 'https://pay.886pay.com/api/merchant_query?time={}&sign={}'

APP_CONF = {
    'KS': {
        'API_KEY': '35a19462-e931-4e18-9005-085788fff78a'
    },
    'ZSQP': {
        'API_KEY': '9382f0b8-9476-4a7a-a13a-3902a289e944'
    },
    'TTQP': {
        'API_KEY': 'a72763b6-06f6-4dab-9597-981aaa2b3633'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(p_data, ts, key):
    '''  生成下单签名 '''
    s = '{}{}{}'.format(p_data, ts, key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().lower()
    _LOGGER.info(u'ks3pay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, json, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}'.format(json, params['time'], key)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest().lower()
    if sign != calculated_sign:
        _LOGGER.info("ks3pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# alipay, wxpay, unionpay, jdpay, qqpay, 目前只支持支付宝.
def _get_pay_type(type):
    if type == 'qq':
        return 'qqpay'
    elif type == 'alipay':
        return 'alipay'
    elif type == 'wxpay':
        return 'wxpay'
    elif type == 'jd':
        return 'jdpay'
    elif type == 'yunshanfu':
        return 'cloudflashpay'
    else:
        return 'unionpay'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(pay.id)),
        ('notify_url', '{}/pay/api/{}/ks3pay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("bill_price", '%.2f' % pay_amount),
        ("payment", _get_pay_type(service)),
        ("info", {
            "device_type": user_info.get('device_type') or 'android',
            "device_id": user_info.get('device_id') or 'IMEI00000001111112222222',
            "device_ip": user_info.get('device_ip') or '171.212.112.44',
            "telephone": user_info.get('tel') or '',
            "name": user_info.get('user_name') or '',
            "player_id": user_info.get('user_id') or '',
            "pay_account": user_info.get('user_alicount') or '',
            "userdata": '100'
        })
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json', 'Connection': 'close'}
    gate_url = _GATEWAY.format(ts, sign)
    _LOGGER.info('ks3pay brefore data: %s', p_data)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    _LOGGER.info('ks3pay rsp data: %s\n%s', gate_url, response.text)
    j = json.loads(response.text)
    url = j['pay_url']
    trade_id = j.get('trade_id')
    if trade_id is not None:
        order_db.fill_third_id(pay.id, trade_id)
    if 'https://qr.alipay.com/' in url:
        _LOGGER.info('ks3pay_qr_alipay_com')
        raise KspayError('ks3pay url qr_alipay_com')
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("ks3pay notify data: %s", data)
    _LOGGER.info("ks3pay notify body: %s", request.body)
    verify_notify_sign(data, request.body, api_key)
    data = json.loads(request.body)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('ks3pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data.get('trade_id')
    total_fee = float(data['receipt_amount'])

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'discount': discount,
    }

    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 10000 and total_fee > 0.0:
        _LOGGER.info('ks3pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    pay_id = pay_order.id
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("op", "query_trade"),
        ("order_id", str(pay_order.id)),
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _QUERY_GATEWAY.format(ts, sign)
    _LOGGER.info('ks3pay brefore data: %s', p_data)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=10)
    _LOGGER.info('ks3pay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        if data['status'] == -1:
            return
        mch_id = pay_order.mch_id
        trade_status = int(data['status'])
        total_fee = float(data['receipt_amount'])
        trade_no = data['trade_id']
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 1表示用户还没支付,
        # 2表示用户已经支付，
        # 3，表示正在回调商户中，
        # 4，表示订单成功完成，
        # 5，表示创建失败，失败原因见reason，
        # 6，回调过多导致失败，
        # 7，其它错误，错误详细见reason
        if trade_status in [2, 4]:
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('ks3pay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)


def query_channel(app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("op", "query_channel"),
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = int(time.time())
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _QUERY_GATEWAY.format(ts, sign)
    print gate_url
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    return response.text


if __name__ == '__main__':
    print query_channel('KS')
